package mi.payment.ui.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import lainey.ui.dialog.TextHintDialog;
import mi.payment.MyApplication;
import mi.payment.R;
import mi.payment.constants.Params;
import mi.payment.controller.BaseSupportController;
import mi.payment.controller.SupportController;
import mi.payment.db.CustomPayDetailModel;
import mi.payment.db.PayDetailModel;
import mi.payment.db.UserInfoModel;
import mi.payment.settings.MerchantSettingsOperation;
import mi.payment.settings.NetworkDataOperations;
import mi.payment.settings.OfflineTransactionOperation;
import mi.payment.settings.SalesSlipPrintSettingsOperation;
import mi.payment.settings.SecurityPasswordSettingsOperation;
import mi.payment.settings.SettlementTransactionOperation;
import mi.payment.settings.SystemParamsOperation;
import mi.payment.settings.TerminalKeyDataOperations;
import mi.payment.settings.TransactionInputPwdOperation;
import mi.payment.settings.TransactionOtherOperation;
import mi.payment.settings.TransactionSwitchOperation;
import mi.payment.utils.MToast;
import mi.payment.utils.ThreadPoolManager;
import mi.payment.utils.print.DataPrinterKernel;
import sunmi.payment.L3.L3BroadcastHelper;
import sunmi.payment.L3.L3ErrorCode;
import sunmi.payment.ui.dialog.LoadDialog;
import sunmi.sunmiui.dialog.EditTextDialog;
import sunmi.sunmiui.utils.LogUtil;

public abstract class ParentActivity extends Activity implements View.OnClickListener {

    private static final String TAG = "ParentActivity";

    public static final String ACTION_TEXT_EXTRA = "payment.ACTION_TEXT_EXTRA";
    public static final String ACTION_CHANGE_DIALOG_TEXT = "payment.ACTION_CHANGE_DIALOG_TEXT";

    public static final String ACTION_CLOSE_APP = "payment.ACTION_CLOSE_APP";
    public static final String ACTION_CLOSE_ACTIVITY = "payment.ACTION_CLOSE_ACTIVITY";
    public static final String ACTION_CLOSE_HOME_ACTIVITY = "payment.close.action_OrdinaryUserHomePageActivity";

    public UserInfoModel mUserInfoModel;
    public CustomPayDetailModel mPayDetailModel;
    public DataPrinterKernel mDatePrinterKernel;

    protected LoadDialog mLoadDialog;
    protected SystemParamsOperation mSystemParamsOperation;
    protected MerchantSettingsOperation mMerchantSettingsOperation;
    protected NetworkDataOperations mNetworkDataOperations;
    protected OfflineTransactionOperation mOfflineTransactionOperation;
    protected SalesSlipPrintSettingsOperation mSalesSlipPrintSettingsOperation;
    protected SecurityPasswordSettingsOperation mSecurityPasswordSettingsOperation;
    protected SettlementTransactionOperation mSettlementTransactionOperation;
    protected TerminalKeyDataOperations mTerminalKeyDataOperations;
    protected TransactionInputPwdOperation mTransactionInputPsdOperation;
    protected TransactionOtherOperation mTransactionOtherOperation;
    protected TransactionSwitchOperation mTransactionSwitchOperation;

    public String clazzName;
    public BaseSupportController mSupportController;

    private boolean keepScreenOn = true;
    private EditTextDialog mEditTextDialog;
    private LocalBroadcastManager localBroadcastManager;

    public Activity mActivity;
    public Context mContext;

    //+tomcat; 20170914; 修改首页不保持屏幕常亮
    public void setKeepScreenOn(boolean keepScreenOn) {
        this.keepScreenOn = keepScreenOn;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = this;
        mContext = getApplicationContext();
        setStatusBarColor();
        MyApplication.initLocaleLanguage();


        // 保持屏幕常亮
        if (keepScreenOn) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
        mSystemParamsOperation = SystemParamsOperation.getInstance();
        mMerchantSettingsOperation = MerchantSettingsOperation.getInstance();
        mNetworkDataOperations = NetworkDataOperations.getInstance();
        mOfflineTransactionOperation = OfflineTransactionOperation.getInstance();
        mSalesSlipPrintSettingsOperation = SalesSlipPrintSettingsOperation.getInstance();
        mSecurityPasswordSettingsOperation = SecurityPasswordSettingsOperation.getInstance();
        mSettlementTransactionOperation = SettlementTransactionOperation.getInstance();
        mTerminalKeyDataOperations = TerminalKeyDataOperations.getInstance();
        mTransactionInputPsdOperation = TransactionInputPwdOperation.getInstance();
        mTransactionOtherOperation = TransactionOtherOperation.getInstance();
        mTransactionSwitchOperation = TransactionSwitchOperation.getInstance();

        mUserInfoModel = UserInfoModel.getInstance();
        mPayDetailModel = PayDetailModel.getInstance();
        mDatePrinterKernel = DataPrinterKernel.INSTANCE();

        mSupportController = new SupportController(this);

        initRegisterReceiver();
        clazzName = getClass().getSimpleName();
    }

    private void initRegisterReceiver() {
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        // 新建intentFilter并给其action标签赋值
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_CLOSE_APP);
        filter.addAction(ACTION_CLOSE_ACTIVITY);
        filter.addAction(ACTION_CLOSE_HOME_ACTIVITY);
        filter.addAction(ACTION_CHANGE_DIALOG_TEXT);
        // 创建广播接收器实例,并注册.将其接收器与action标签进行绑定.
        localBroadcastManager.registerReceiver(receiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            localBroadcastManager.unregisterReceiver(receiver);
        }
        if (mLoadDialog != null) {
            mLoadDialog.dismiss();
            mLoadDialog = null;
        }
        if (mEditTextDialog != null) {
            mEditTextDialog.dismiss();
            mEditTextDialog = null;
        }
    }

    /**
     * 设置通知栏背景色
     */
    protected void setStatusBarColor() {
        Window window = getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
    }

    /**
     * 设置通知栏背景色
     */
    protected void setStatusBarColor(int resId) {
        Window window = getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(resId);
        }
    }

    public void showLoadingDialog() {
        showLoadingDialog(null);
    }

    public void showLoadingDialog(int resId) {
        String msg = getString(resId);
        showLoadingDialog(msg);
    }

    public void showLoadingDialog(String msg) {
        try {
            getLoadingDialog(msg);
            mLoadDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void dismissLoadingDialog() {
        try {
            if (mLoadDialog != null) {
                mLoadDialog.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public LoadDialog getLoadingDialog() {
        if (mLoadDialog != null) {
            return mLoadDialog;
        }
        return getLoadingDialog("");
    }

    public LoadDialog getLoadingDialog(String msg) {
        if (mLoadDialog == null) {
            mLoadDialog = new LoadDialog(this, msg);
        } else {
            mLoadDialog.setMessage(msg);
        }
        return mLoadDialog;
    }

    public LoadDialog getLoadingDialog(int redId) {
        String text = getString(redId);
        return getLoadingDialog(text);
    }

    public void setLoadDialogMsg(String msg) {
        getLoadingDialog(msg);
    }

    public void sendCloseActivityBroadcast() {
        Intent intent = new Intent(ACTION_CLOSE_ACTIVITY);
        localBroadcastManager.sendBroadcast(intent);
    }

    // 发送关闭首页的广播
    public void sendCloseHomeActivityBroadcast() {
        Intent intent = new Intent(ACTION_CLOSE_HOME_ACTIVITY);
        localBroadcastManager.sendBroadcast(intent);
    }

    public void sendCloseAppBroadcast() {
        Intent intent = new Intent(ACTION_CLOSE_APP);
        localBroadcastManager.sendBroadcast(intent);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            LogUtil.i(TAG, "activity:" + clazzName);
            String action = intent.getAction();
            if (action == null) return;
            switch (action) {
                case ACTION_CHANGE_DIALOG_TEXT:
                    String extra = intent.getStringExtra(ACTION_TEXT_EXTRA);
                    setLoadDialogMsg(extra);
                    break;
                case ACTION_CLOSE_ACTIVITY:
                    boolean judge = "HomeInputMoneyActivity".equals(clazzName) ||
                            "PreAuthorizeMainActivity".equals(clazzName) ||
                            "HomePageActivity".equals(clazzName);
                    if (judge) {
                        LogUtil.i(TAG, "回到一级菜单首页");
                    } else {
                        finish();
                    }
                    break;
                case ACTION_CLOSE_APP:
                    finish();
                    break;
                case ACTION_CLOSE_HOME_ACTIVITY:
                    judge = "LoginActivity".equals(clazzName);
                    if (judge) {
                        LogUtil.i(TAG, "现在是登陆界面");
                    } else {
                        finish();
                    }
                    break;
            }
        }

    };

    public void runOnUI(Runnable run) {
        handler.post(run);
    }

    public void runOnUI(Runnable r, int delay) {
        handler.postDelayed(r, delay);
    }

    public void removeCallbacks(Runnable callback) {
        handler.removeCallbacks(callback);
    }

    public void removeCallbacksAndMessages(Object token) {
        handler.removeCallbacksAndMessages(token);
    }

    public void executeTask(Runnable run) {
        ThreadPoolManager.executeInCachePool(run);
    }

    public void showToast(int resId) {
        MToast.showToast(resId);
    }

    public void showToast(String msg) {
        MToast.showToast(msg);
    }

    public void showToast(int resId, int duration) {
        MToast.showToast(resId, duration);
    }

    public void showToast(String msg, int duration) {
        MToast.showToast(msg, duration);
    }

    @Override
    public void onClick(View v) {
    }

    public boolean checkEmpty(String str) {
        boolean empty = TextUtils.isEmpty(str);
        if (empty) {
            showToast(R.string.error_input);
            return false;
        }
        return true;
    }

    public void openActivity(Class clazz) {
        openActivity(new Intent(this, clazz), false);
    }

    public void openActivity(Intent intent) {
        openActivity(intent, false);
    }

    public void openActivity(Class clazz, boolean finishSelf) {
        openActivity(new Intent(this, clazz), finishSelf);
    }

    public void openActivity(Intent intent, boolean finishSelf) {
        startActivity(intent);
        if (finishSelf) {
            finish();
        }
    }

    public boolean checkInt(String str, int upValue, int downValue) {
        int value;
        try {
            value = Integer.parseInt(str);
            if (value > upValue || value < downValue) {
                String text = getString(R.string.int_check_error) + downValue + "-" + upValue;
                showToast(text);
                return false;
            } else
                return true;
        } catch (NumberFormatException e) {
            showToast(R.string.error_input);
            return false;
        }
    }

    protected void showSoftKeyboard(EditTextDialog mEditTextDialog) {
        this.mEditTextDialog = mEditTextDialog;
        handler.sendEmptyMessageDelayed(0x01, 50);
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x01) {
                mEditTextDialog.showSoftInput();
            }
        }

    };

    /**
     * 处理L3的返回
     */
    public void handleL3Back(L3ErrorCode errorCode) {
        if (Params.sL3Params != null) {
            sendCloseAppBroadcast();
            L3BroadcastHelper.sendFailedBroadcast(this, errorCode);
        }
    }


    private TextHintDialog mTextHintDialog;

    public void showTextHintDialog(int resId) {
        String text = getString(resId);
        showTextHintDialog(text);
    }

    public void showTextHintDialog(String msg) {
        if (mTextHintDialog == null) {
            mTextHintDialog = new TextHintDialog(this);
            mTextHintDialog.setOKText(R.string.ok);
            mTextHintDialog.setTitle(R.string.hint);
            mTextHintDialog.setOnClickListener(
                    v -> dismissTextHintDialog()
            );
            mTextHintDialog.setCancelable(true);
            mTextHintDialog.setCanceledOnTouchOutside(true);
        }
        try {
            mTextHintDialog.setMessage(msg);
            mTextHintDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void dismissTextHintDialog() {
        if (mTextHintDialog != null) {
            try {
                mTextHintDialog.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
